
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>涨停板分析与排序系统 v1.0</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        let lastLogCount = 0;

        function startAnalysis(event) {
            event.preventDefault();
            const date = document.getElementById('date').value;
            const button = document.getElementById('start-button');
            const logArea = document.getElementById('log-area');
            logArea.value = '';
            button.disabled = true;
            button.textContent = '分析中...';
            logArea.value += '发起分析请求...\n';
            console.log('发起分析请求:', date);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/analyze', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        try {
                            const result = JSON.parse(xhr.responseText);
                            if (result.error) {
                                alert('错误：' + result.error);
                                logArea.value += '错误：' + result.error + '\n';
                            } else {
                                logArea.value += '分析已启动，请等待结果...\n';
                                console.log('分析已启动');
                            }
                        } catch (e) {
                            logArea.value += '错误：解析响应失败 - ' + e.message + '\n';
                            console.error('解析响应失败:', e);
                        }
                    } else {
                        alert('请求失败，状态码：' + xhr.status);
                        logArea.value += '错误：请求失败，状态码：' + xhr.status + '\n';
                        console.error('请求失败，状态码:', xhr.status);
                    }
                    button.disabled = false;
                    button.textContent = '开始分析与排序';
                }
            };
            xhr.onerror = function() {
                logArea.value += '错误：网络请求失败，请检查网络\n';
                alert('网络请求失败，请检查网络');
                console.error('网络请求失败');
                button.disabled = false;
                button.textContent = '开始分析与排序';
            };
            xhr.send(`date=${date}`);
        }

        function fetchLogs() {
            console.log('请求日志...');
            fetch('/logs')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('日志请求失败，状态码：' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('收到日志:', data.logs);
                    const logArea = document.getElementById('log-area');
                    const manualLinkContainer = document.getElementById('manual-link');
                    data.logs.forEach((log, index) => {
                        console.log(`处理日志[${index + lastLogCount}]: ${log}`);
                        logArea.value += log + '\n';
                        if (log.startsWith('IMAGE:')) {
                            const fileName = log.replace('IMAGE:', '');
                            logArea.value += `图片生成，将在新窗口打开：${fileName}\n`;
                            console.log('检测到图片，打开新窗口:', fileName);
                            // 在新窗口打开图片
                            const imageUrl = `/output/${fileName}?t=${new Date().getTime()}`;
                            const imageWindow = window.open(imageUrl, '_blank');
                            if (!imageWindow) {
                                logArea.value += '错误：无法打开新窗口，请检查浏览器弹出窗口设置或手动打开\n';
                                console.error('无法打开新窗口');
                                // 提供手动打开链接
                                manualLinkContainer.innerHTML = `<a href="${imageUrl}" target="_blank" class="text-blue-500 hover:underline">手动打开图片：${fileName}</a>`;
                            } else {
                                logArea.value += `新窗口已打开图片：${fileName}\n`;
                                console.log('新窗口打开成功:', fileName);
                            }

                            // 触发自动下载
                            const downloadLink = document.createElement('a');
                            downloadLink.href = `/download/image/${fileName}`;
                            downloadLink.download = fileName;
                            document.body.appendChild(downloadLink);
                            setTimeout(() => {
                                downloadLink.click();
                                logArea.value += '已触发图片下载，请检查浏览器下载提示\n';
                                console.log('触发下载:', fileName);
                                document.body.removeChild(downloadLink);
                            }, 500);
                        }
                    });
                    lastLogCount += data.logs.length;
                    logArea.scrollTop = logArea.scrollHeight;
                })
                .catch(error => {
                    console.error('获取日志错误:', error);
                    const logArea = document.getElementById('log-area');
                    logArea.value += '错误：获取日志失败 - ' + error.message + '\n';
                });

            setTimeout(fetchLogs, 1000);
        }

        window.onload = () => {
            console.log('页面加载完成，开始获取日志');
            fetchLogs();
            document.getElementById('start-button').addEventListener('click', startAnalysis);
        };
    </script>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
    <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-2xl">
        <h1 class="text-2xl font-bold mb-4 text-center">涨停板分析与排序系统 v1.0</h1>
        <div class="mb-4">
            <label for="date" class="block text-sm font-medium text-gray-700">选择日期（建议近期交易日，如 2024-10-17）:</label>
            <input type="date" id="date" name="date" value="{{ default_date }}" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
        </div>
        <button id="start-button" class="w-full bg-indigo-600 text-white py-2 px-4 rounded-md hover:bg-indigo-700">开始分析与排序</button>
        <div class="mt-4">
            <label for="log-area" class="block text-sm font-medium text-gray-700">日志输出:</label>
            <textarea id="log-area" class="mt-1 block w-full h-64 border-gray-300 rounded-md shadow-sm" readonly></textarea>
        </div>
        <div id="manual-link" class="mt-4 text-center"></div>
    </div>
</body>
</html>
